package cn.demomaster.quickrouter.lifecycle;

import android.app.Activity;
import android.util.Log;

import androidx.fragment.app.Fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import cn.demomaster.quickrouter.BuildConfig;

public class LifecycleRecorder {
    // 单例模式保证全局访问
    private static LifecycleRecorder instance;

    public static LifecycleRecorder getInstance() {
        if (instance == null) {
            instance = new LifecycleRecorder();
        }
        return instance;
    }

    private LifecycleRecorder() {
    }

    // 使用 ConcurrentHashMap 保证线程安全
    private final Map<String, LifecycleTrace> latestEvents = new LinkedHashMap<>();

    public List<LifecycleTrace> getLifecycleTraces() {
        List<LifecycleTrace> list = new ArrayList<>();
        for (Map.Entry<String, LifecycleTrace> entry : latestEvents.entrySet()) {
            LifecycleTrace event = entry.getValue();
            list.add(event);
        }
        return list;
    }

    // 记录生命周期事件
    public void recordEvent(Activity activity, LifecycleStateType lifecycleStateType) {
        String key = getActivityKey(activity);

        // 获取或创建事件记录
        LifecycleTrace event = latestEvents.computeIfAbsent(key,
                k -> new LifecycleTrace(activity));

        event.addLifecycleEvent(lifecycleStateType);

        // 特殊状态处理
        if(lifecycleStateType==LifecycleStateType.onActivityDestroyed){
            event.setDestroyed(true);
            // 销毁后从缓存移除
            latestEvents.remove(key);
        }

        // DEBUG模式下打印当前缓存状态
        if (BuildConfig.DEBUG) {
            //printLatestEvents();
        }
    }

    // 记录生命周期事件
    public void recordFragmentEvent(Fragment fragment, LifecycleStateType lifecycleStateType) {
        String key = getFragmentKey(fragment);

        // 获取或创建事件记录
        LifecycleTrace event = latestEvents.computeIfAbsent(key,
                k -> new LifecycleTrace(fragment));

        event.addLifecycleEvent(lifecycleStateType);

        // 特殊状态处理
        if(lifecycleStateType==LifecycleStateType.onFragmentDestroyed){
            event.setDestroyed(true);
            // 销毁后从缓存移除
            latestEvents.remove(key);
        }
    }

    private String getActivityKey(Activity activity) {
        // 使用类名+哈希码作为唯一标识
        return activity.getClass().getName() + "@" + System.identityHashCode(activity);
    }
    private String getFragmentKey(Fragment fragment) {
        // 使用类名+哈希码作为唯一标识
        return fragment.getClass().getName() + "@" + System.identityHashCode(fragment.getClass())+"-"+fragment.getClass().getName()+"@"+fragment.hashCode();
    }

}


